package cn.virens.common.apifox.apifox.util;

import cn.virens.common.apifox.apifox.ApifoxType;
import cn.virens.common.apifox.apifox.build.ApiFoxCollectionParamItem;
import cn.virens.common.util.exception.APIException;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ValueConstants;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ApifoxUtilParam {
    /**
     * 获取请求参数
     */
    public static List<ApiFoxCollectionParamItem> getParamItem(Method method) throws APIException {
        return Arrays.stream(method.getParameters()).map(parameter -> {
            RequestParam pm = parameter.getAnnotation(RequestParam.class);
            if (pm == null || StrUtil.isEmpty(name(pm))) return null;

            ApiFoxCollectionParamItem item = new ApiFoxCollectionParamItem();
            item.setType(ApifoxType.formatType(parameter.getType()));
            item.setRequired(pm.required());
            item.setExample(example(pm));
            item.setName(name(pm));

            return item;
        }).filter(a -> a != null).collect(Collectors.toList());
    }

    /**
     * 获取注解默认值
     */
    private static String example(RequestParam rp) throws APIException {
        if (!ValueConstants.DEFAULT_NONE.equals(rp.defaultValue())) {
            return rp.defaultValue();
        } else {
            return "";
        }
    }

    /**
     * 获取注解name(可选value)值
     */
    private static String name(RequestParam rp) throws APIException {
        if (StrUtil.isNotEmpty(rp.value())) {
            return rp.value();
        } else {
            return rp.name();
        }
    }
}
